import userService from '@/api/modules/user.js'
import defAva from '@/assets/images/profile.jpg'
import { getToken, removeToken, setToken } from '@/utils/auth.js'
import { isHttp } from '@/utils/validate.js'
import { isEmpty } from 'lodash-es'

const useUserStore = defineStore('users', () => {
  const token = ref(getToken() || '')
  const roles = ref([])
  const permissions = ref([])
  const userInfo = ref({})
  const userId = ref('')
  const userAvatar = ref('')
  const userName = ref('')

  function authLogin(userInfo) {
    return new Promise((resolve, reject) => {
      const username = userInfo?.username?.trim()
      const password = userInfo?.password
      const code = userInfo?.code
      const uuid = userInfo?.uuid
      userService.login({
        username,
        password,
        code,
        uuid,
      }).then(async (res) => {
        const data = res.data
        setToken(data.token)
        token.value = data.token
        resolve(data)
        await getInfo()
      }).catch((error) => {
        reject(error)
      })
    })
  }

  function authRegister(userInfo) {
    return new Promise((resolve, reject) => {
      userService.register(userInfo).then(async (res) => {
        const data = res.data
        setToken(data.token)
        token.value = data.token
        resolve(data)
        await getInfo()
      }).catch((error) => {
        reject(error)
      })
    })
  }

  function authSmsLogin(userInfo) {
    return new Promise((resolve, reject) => {
      userService.smsLogin(userInfo).then(async (res) => {
        const data = res.data
        setToken(data.token)
        token.value = data.token
        resolve(data)
        await getInfo()
      }).catch((error) => {
        reject(error)
      })
    })
  }

  function getInfo() {
    return new Promise((resolve, reject) => {
      userService.getInfo().then((res) => {
        const data = res.data
        const user = data.user
        let avatar = user.avatar || ''
        if (!isHttp(avatar)) {
          avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_API_BASEURL + avatar
        }
        if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          roles.value = data.roles
          permissions.value = data.permissions
        }
        else {
          roles.value = ['ROLE_DEFAULT']
        }
        userInfo.value = user
        userName.value = user.username
        userId.value = user.userId
        userAvatar.value = avatar
        resolve(data)
      }).catch((error) => {
        reject(error)
      })
    })
  }

  function logOut() {
    return new Promise((resolve, reject) => {
      userService.logout().then(() => {
        token.value = ''
        roles.value = []
        permissions.value = []
        userName.value = ''
        userId.value = ''
        userAvatar.value = ''
        userInfo.value = {}
        removeToken()
        resolve()
      }).catch((error) => {
        reject(error)
      })
    })
  }

  return {
    token,
    roles,
    permissions,
    userInfo,
    userId,
    userAvatar,
    authLogin,
    authRegister,
    authSmsLogin,
    getInfo,
    logOut,
  }
})

export default useUserStore
